<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--企业数据-->
      <!-- <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col> -->
      <!--小区数据-->
      <el-col :span="24" :xs="24">
        <el-card class="box-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="片区名称" prop="areaName">
              <el-input v-model="queryParams.areaName" placeholder="请输入片区名称" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['system:areainfo:add']">新增</el-button>
            </el-col>

            <!-- <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['fileManagement:areaDefinition:edit']">修改</el-button>
            </el-col> -->
            <!-- <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                @click="handleDelete('批量')" v-hasPermi="['fileManagement:areaDefinition:remove']">删除</el-button>
            </el-col> -->
            <!-- <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                v-hasPermi="['fileManagement:areaDefinition:import']">导入</el-button>
            </el-col> -->
            <!--            <el-col :span="1.5">-->
            <!--              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"-->
            <!--                v-hasPermi="['system:areainfo:export']">导出</el-button>-->
            <!--            </el-col>-->
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-if="refreshTable" v-loading="loading" :data="areaList" row-key="id"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="片区名称" align="left" key="areaName" prop="areaName" :show-overflow-tooltip="true" />
            <el-table-column label="上级片区" align="center" key="parentName" prop="parentName"
              :show-overflow-tooltip="true" />
            <el-table-column label="类型" align="center" key="type" prop="type" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.type == '1'">片区</span>
                <span v-if="scope.row.type == '2'">小区</span>
              </template>
            </el-table-column>
            <el-table-column label="详细地址" align="center" key="address" prop="address" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:areainfo:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:areainfo:remove']">删除</el-button>
                <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
                  v-hasPermi="['system:areainfo:add']">新增</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改小区配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" filterable placeholder="请选类型" style="width:100%">
                <el-option label="片区" value="1"> </el-option>
                <el-option label="小区" value="2"> </el-option>

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级片区" prop="parentName">
              <el-input v-model="form.parentName" placeholder="请输入上级片区" maxlength="30" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名称" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="省市区" prop="nickName">
              <el-cascader placeholder="试试搜索：指南" :options="options" filterable style="width:100%"></el-cascader>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  deptTreeSelect,
} from "@/api/system/user";
import { areaList, areaInfo, addArea, updateArea, delArea, exportArea, areaTreeList } from "@/api/fileManagement/areainfo.js"
import { getToken } from "@/utils/auth";
import { listDept } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'

export default {
  name: "areaDefinition",
  components: { Treeselect },
  data() {
    return {
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      idName: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格树数据
      areaList: [],
      // 片树选项
      areaOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "areaName",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaName: undefined,

      },
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: "片区名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "小区名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选企业树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    form: {
      deep: true,
      handler(val) {
        this.form = val
      }
    }
  },
  created() {
    this.getList();
    // this.getAreList();
  },
  methods: {
    /**查询列表**/
    getList() {
      this.loading = true;
      areaList(this.queryParams).then((response) => {
        this.areaList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },


    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    // handleNodeClick(data) {
    //   this.queryParams.deptId = data.id;
    //   this.handleQuery();
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.idName = selection.map((item) => item.areaName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(info) {
      this.reset();
      console.log(info)
      if (info) {
        this.form.parentName = info.areaName
        this.form.parentId = info.id
        this.open = true;
        this.title = "添加小区";
      } else {
        this.open = true;
        this.title = "添加小区";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log(row)
      areaInfo(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小区";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateArea(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArea(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let userIds = ''
      let userName = ''
      if (row == '批量') {
        userIds = this.ids.join(',')
        userName = this.idName.join(',')
      } else {
        userIds = row.id
        userName = row.areaName
      }
      this.$modal
        .confirm('是否确认删除片区名称为"' + userName + '"的数据项？')
        .then(function () {
          return delArea(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      let param = {
        id: this.ids
      }
      this.download(
        "system/areainfo/export",
        {
          ...this.queryParams, ...param
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "小区导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
